package com.gack.netty.constant;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.stereotype.Component;

import com.gack.netty.vo.ChannelInfoVO;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * 
* @ClassName: ConstantChannels 
* @Description: TODO(保存所有通道  暂时用静态Map集合存储 包括了对于集合必要的操作) 
* @author (ZhangXinYu)  
* @date 2018年8月30日 下午12:24:57 
* @version V1.0
 */
@Component
public class ConstantChannels {
	private static Map<Channel, ChannelInfoVO> map = new HashMap<>();
	
	/**
	 * build一个空的ChannelGroup
	 */
	public static ChannelGroup buildEmptyChannelGroup(){
		return new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
	}
	
	/**
	 * 添加管道
	 */
	public static void push(Channel channel, ChannelInfoVO channelInfo){
		map.put(channel, channelInfo);
	}
	
	/**
	 * 获取管道对应信息
	 */
	public static ChannelInfoVO get(Channel channel){
		return map.get(channel);
	}
	
	/**
	 * 根据管道别名获取管道
	 */
	public static List<Channel> getByAssets(String assets){
		List<Channel> channels = null;
		channels = map.entrySet().stream().filter(entry -> entry.getValue().getAssets().equals(assets))
				.map(entry -> entry.getKey()).collect(Collectors.toList());
		return channels;
	}
	
	/**
	 * 根据管道地址获取管道(地址 = host:port)
	 */
	public static List<Channel> getByAddress(String address){
		List<Channel> channels = null;
		channels = map.entrySet().stream().filter(entry -> entry.getValue().getAddress().equals(address))
				.map(entry -> entry.getKey()).collect(Collectors.toList());
		return channels;
	}
	
	/**
	 * 根据ip地址获取管道 （地址 = host  不包含port）
	 */
	public static List<Channel> getByHost(String host){
		List<Channel> channels = null;
		channels = map.entrySet().stream().filter(entry -> entry.getValue().getAddress().contains(host))
				.map(entry -> entry.getKey()).collect(Collectors.toList());
		return channels;
	}
	
	/**
	 * 获取所有管道
	 */
	public static List<Channel> allChannels(){
		return map.keySet().stream().collect(Collectors.toList());
	}
	
	/**
	 * 将管道移除
	 */
	public static void remove(Channel channel){
		map.remove(channel);
	}
	
	/**
	 * 根据别名移除管道
	 */
	public static void removeByAssets(String assets){
		map.entrySet().stream().filter(entry -> entry.getValue().getAssets().equals(assets))
			.forEach(entry -> map.remove(entry.getKey()));
	}
	
	/**
	 * 根据地址移除管道
	 */
	public static void removeByAddress(String address){
		map.entrySet().stream().filter(entry -> entry.getValue().getAddress().equals(address))
			.forEach(entry -> map.remove(entry.getKey()));
	}
	
	/**
	 * 管道是否存在
	 */
	public static boolean hasChannel(Channel channel){
		return map.containsKey(channel);
	}
	
	/**
	 * 别名是否已存在
	 */
	public static boolean hasAssets(String assets){
		return map.values().stream().anyMatch(channelInfo -> channelInfo.getAssets().equals(assets));
	}
	
}
